package com.example.hinfc;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.Arrays;

public class CardActivity extends AppCompatActivity {
    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private TextView tvNumber;
    private View btnRead;
    private static String LOG_TAG = "CardActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reader_activity);

        tvNumber = findViewById(R.id.tvNumber);
        btnRead = findViewById(R.id.btnRead);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, "NFC not supported on this device", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        pendingIntent = PendingIntent.getActivity(CardActivity.this, 0,
                new Intent(CardActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(LOG_TAG, "onNewIntent....");

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag != null) {
            String number = readNfcTag(tag);
            if (number != null) {
                tvNumber.setText("Received Number: " + number);
                Toast.makeText(this, "Transaction successful", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "tag is null!!!", Toast.LENGTH_SHORT).show();
        }
    }

    private String readNfcTag(Tag tag) {
        Log.i(LOG_TAG, "readNfcTag....");
        Toast.makeText(this, "readNfcTag....", Toast.LENGTH_SHORT).show();

        Ndef ndef = Ndef.get(tag);
        try {
            if (ndef != null) {
                Log.i(LOG_TAG, "Ndef.get success");
                ndef.connect();
                NdefMessage ndefMessage = ndef.getNdefMessage();
                if (ndefMessage != null) {
                    NdefRecord[] records = ndefMessage.getRecords();
                    Toast.makeText(this, "records = " +  records.toString(), Toast.LENGTH_SHORT).show();
                    for (NdefRecord record : records) {
                        if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
                            byte[] payload = record.getPayload();
                            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
                            int languageCodeLength = payload[0] & 0x3F;
                            return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
                        }
                    }
                } else {
                    Log.i(LOG_TAG, "ndefMessage is null!!!!!!");
                    return "404";
                }
            } else {
                Toast.makeText(this, "ndef is null!!!!!!!!!" , Toast.LENGTH_SHORT).show();
            }
        }  catch (IOException| FormatException e) {
            e.printStackTrace();
            Toast.makeText(this, "error message : " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return "400";
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter != null) {
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null) {
            nfcAdapter.disableForegroundDispatch(this);
        }
    }
}
